package com.yang.concurrency.chapter7;

/**
 * @Author: 血魔
 * @Date: Created in 16:40 2021/12/12
 * @Version: $
 */
public class ThreadService {
    private static long mills = 500;
    private static Thread executeThread;
    private static boolean finished = false;

    public void execute(Runnable task){
        executeThread = new Thread(){
            @Override
            public void run() {
                Thread runner = new Thread(task);
                runner.setDaemon(true);

                runner.start();
                try {
                    runner.join();
                    finished = true;
                } catch (InterruptedException e) {
                }
            }
        };
        executeThread.start();
    }

    public static void main(String[] args) {
        long currentTime = System.currentTimeMillis();
        while(!finished){
            if((System.currentTimeMillis() - currentTime) >= mills){
                System.out.println("任务超时，需要结束他！");
                executeThread.interrupt();
                break;
            }

            try{
                Thread.sleep(1);
            } catch (InterruptedException e) {
                System.out.println("执行线程被打断！！");
                e.printStackTrace();
            }
        }
    }

    public void shutdown(long mills) {
        long currentTime = System.currentTimeMillis();
        while(!finished){
            if((System.currentTimeMillis() - currentTime) >= mills){
                System.out.println("任务超时，需要结束他！");
                executeThread.interrupt();
                break;
            }
            try {
                Thread.sleep(1);
            } catch (InterruptedException e) {
                System.out.println("执行线程被打断！！");
                e.printStackTrace();
            }
        }
    }
}
